package wang.chunfan.springcloud.learning.nacos.user.server.service.impl;

import org.springframework.stereotype.Service;
import wang.chunfan.springcloud.learning.consul.user.server.model.User;
import wang.chunfan.springcloud.learning.consul.user.server.service.UserService;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/5/22 10:08
 **/
@Service
public class UserServiceImpl implements UserService {

    private List<User> userList;

    @Override
    public void insert(User user) {
        boolean isExists = userList.stream()
                .anyMatch(userItem -> userItem.getId().equals(user.getId()));
        if (isExists) {
            update(user);
        } else {
            userList.add(user);
        }
    }

    @Override
    public void delete(Long id) {
        userList.remove(get((id)));
    }

    @Override
    public void update(User user) {
        userList.stream()
                .filter(userItem -> userItem.getId().equals(user.getId()))
                .forEach(userItem -> {
                    userItem.setUsername(user.getUsername());
                    userItem.setPassword(user.getPassword());
                });
    }

    @Override
    public User get(Long id) {
        return userList.stream()
                .filter(userItem -> userItem.getId().equals(id))
                .findFirst().orElse(null);

    }

    @Override
    public List<User> getByUsername(String username) {
        return userList.stream()
                .filter(userItem -> userItem.getUsername().equals(username))
                .collect(Collectors.toList());
    }

    @Override
    public List<User> listByIds(List<Long> ids) {
        return userList.stream()
                .filter(userItem -> ids.contains(userItem.getId()))
                .collect(Collectors.toList());
    }

    @PostConstruct
    public void initData() {
        userList = new ArrayList();
        userList.add(new User(3L, "张三", "1"));
        userList.add(new User(4L, "李四", "2"));
        userList.add(new User(5L, "王五", "5"));

    }
}
